/* global window */
import modelExtend from 'dva-model-extend'
import * as permissionService from './services/permissions'
import * as roleService from '../role/services/roles'
import * as empService from '../employee/services/employees'
import {pageModel} from 'utils/model'
import {arrayToTree} from "utils"

const {getModals} = permissionService

const initSelected = (datas, selectedRowKeys) => {
  if (datas && datas.length > 0) {
    for (let i = 0; i < datas.length; i++) {
      let item = datas[i]

      if (item.authorized) {
        selectedRowKeys.push(item.id)
      }
      if (item.children) {
        initSelected(item.children, selectedRowKeys)
      }
    }
  }
}

export default modelExtend(pageModel, {
  namespace: 'permission',

  state: {
    selectedRowKeys: [],
    expandedRowKeys: [],
    memberSelectedKeys: [],
    selectedRoleId: -1,
    memberModalVisible: false,
    modals: [],
    roles: [],
    buttons: [],
    data: {},
  },

  subscriptions: {
    setup ({dispatch, history}) {
      history.listen((location) => {
        if (location.pathname === '/permission') {
          const payload = location.query
          dispatch({
            type: 'getModals',
            payload,
          })

          dispatch({
            type: 'getRoles',
          })
        }
      })
    },
  },

  effects: {

    * addMembers ({payload = {}}, {call, put}) {
      const data = yield call(permissionService.addMembers, payload)

      if (data.code !== 0) {
        if (data.message && data.message === 'OK') {
          data.message = '添加成员失败'
        }
        throw data
      }
    },

    * noRoleMembers ({payload = {}}, {call, put}) {
      const response = yield call(empService.query, payload)
      const {data} = response

      if (response) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.records,
            pagination: {
              current: Number(payload.current) || 1,
              pageSize: Number(payload.size) || 10,
              total: data.total,
            },
          },
        })
      }
    },

    * deleteMembers ({payload = {}}, {call, put}) {
      const data = yield call(permissionService.deleteMembers, payload)

      if (data.code !== 0) {
        if (data.message && data.message === 'OK') {
          data.message = '删除成员失败'
        }
        throw data
      }
    },

    * buttonAuthorize ({payload = {}}, {call, put}) {
      const data = yield call(permissionService.buttonAuthorize, payload)

      if (data.code === 0) {
        yield put({
          type: 'buttons',
          payload: {...payload},
        })
      } else {
        if (data.message && data.message === 'OK') {
          data.message = '授权失败'
        }
        throw data
      }
    },

    * dataAuthorize ({payload = {}}, {call, put}) {
      const data = yield call(permissionService.dataAuthorize, payload)

      if (data.code === 0) {
        yield put({
          type: 'datas',
          payload: {...payload},
        })
      } else {
        if (data.message && data.message === 'OK') {
          data.message = '授权失败'
        }
        throw data
      }
    },

    * datas ({payload = {}}, {call, put}) {
      const {roleId} = payload
      const response = yield call(permissionService.getDatas, payload)
      const {data} = response

      if (response) {
        yield put({
          type: 'updateState',
          payload: {
            data: data,
            selectedRoleId: roleId,
          },
        })
      }
    },

    * buttons ({payload = {}}, {call, put}) {
      const {roleId} = payload
      const response = yield call(permissionService.getButtons, payload)
      const {data} = response

      if (response) {
        yield put({
          type: 'updateState',
          payload: {
            buttons: data,
            selectedRoleId: roleId,
          },
        })
      }
    },

    * modalAuthorize ({payload = {}}, {call}) {
      const data = yield call(permissionService.modalAuthorize, payload)
      if (data.code !== 0) {
        if (data.message && data.message === 'OK') {
          data.message = '授权失败'
        }
        throw data
      }
    },

    * getRoles ({payload = {}}, {call, put}) {
      const roleResp = yield call(roleService.list, payload)
      const {data} = roleResp
      if (roleResp && roleResp.code === 0) {
        yield put({
          type: 'updateState',
          payload: {
            roles: data,
          },
        })
      }
    },

    * getModals ({payload = {}}, {call, put}) {
      const {roleId} = payload
      const response = yield call(getModals, payload)
      const {data} = response
      if (response && data) {
        const selectedRowKeys = []
        initSelected(data, selectedRowKeys)
        const modalTree = arrayToTree(data, 'id', 'mpid')

        yield put({
          type: 'updateState',
          payload: {
            modals: modalTree,
            selectedRoleId: roleId,
            selectedRowKeys,
          },
        })
      }
    },

    * multiDelete ({payload}, {call, put}) {
      const data = yield call(permissionService.remove, payload)
      if (data.success) {
        yield put({type: 'updateState', payload: {selectedRowKeys: []}})
      } else {
        throw data
      }
    },

  },

  reducers: {

    showMemberModal (state, {payload}) {
      return {...state, ...payload, memberModalVisible: true}
    },

    hideMemberModal (state) {
      return {...state, memberModalVisible: false}
    },

    changeExpand (state, {payload}) {
      const {expandedRowKeys} = state
      const {expanded, key} = payload

      if (expanded) {
        expandedRowKeys.push(key)
      } else {
        expandedRowKeys.remove(key)
      }
      return {
        ...state,
      }
    },

  },
})
